package com.kehutong.house.service;


import com.kehutong.common.DoveClient;
import com.kehutong.common.permission.DataPermissionQuery;
import com.kehutong.common.permission.PermissionNameDto;
import com.kehutong.common.util.Token;
import com.kehutong.house.entity.Community;
import com.kehutong.house.entity.House;
import com.kehutong.house.util.CompareUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;

import com.kehutong.house.entity.Building;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindOne;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@WebService("/basic/building/service")
public class BuildService {
	private static final Logger logger = LoggerFactory.getLogger(BuildService.class);
	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private CommunityService communityService;
	@Inject
	private DoveClient doveClient;
	@Inject
	private HouseService houseService;

	@ReqMapping("/list")
	public Object list(JSONObject jsonObject) {
		return jdbcSession.findArray(Building.class)
				.in(jsonObject, "id")
				.eq(jsonObject,  "communityNo")
				.like(jsonObject, "name","employeeNos")
				.eq("deleted", false)
				.exe();
	}

	public Object permissionQuery(JSONObject jsonObject) {
		FindArray<Building> find = jdbcSession.findArray(Building.class)
				.eq(jsonObject, "communityNo")
				.eq("deleted", false)
				.order("name", "ASC");


		String name = jsonObject.getString("name");
		String unitName = jsonObject.getString("unitName");
		if(Objects.nonEmpty(name) && Objects.nonEmpty(unitName)){
			find.markBegin().like(jsonObject,"name").or()
					.like(jsonObject, "unitName")
					.markEnd();
		}


		PermissionNameDto dto = houseService.getBuildPermissionNameDto();
		DataPermissionQuery.setAllDataSql(find, dto, null);
		List<Building> list = find.exe();
		return list;
	}

	public List<Building> list(String communityNo) {
		List<Building> builds = jdbcSession.findArray(Building.class)
				.eq("communityNo", communityNo)
				.eq("deleted", false)
				.order("name", "asc")
				.order("unitName", "asc")
				.exe();

		Collections.sort(builds, new Comparator<Building>() {
			@Override
			public int compare(Building o1, Building o2) {
				String a = o1.getName();
				String b = o2.getName();
				return CompareUtil.compareResult(a, b);
			}
		});

		return builds;
	}

    @ReqMapping("/get")
    public Object get(Building item) {
    	return item;
    }

    @ReqMapping("/save")
	public Object save(Token token, Building building) throws Exception {
		FindOne<Building> find = jdbcSession.findOne(Building.class)
				.eq("deleted", false)
				.eq("communityNo", building.getCommunityNo())
				.eq("name", building.getName());

		if(Objects.nonEmpty(building.getUnitName())){
			find.eq("unitName", building.getUnitName());
		}

		Building item = find.exe();

		if(Objects.nonNull(item)){
			return Result.error(0, "当前小区下已有相同的楼栋信息，请修改后重试");
		}

		Community com = Pool.get(Community.class, building.getCommunityNo());
		building.setDepartmentNo(com.getParent_id());
		building.setDepartmentNos(com.getParent_ids());
		building.setCreate_by(token.getUsername());
		building.setCreateUserId(token.getUuid());
		building.setCreateDepartment(token.getDepartments());
		building.setCreateChildDepartment(getChildDepartments(token.getDepartments()));

		jdbcSession.insert(building);
		return Result.success(building);
	}

    @ReqMapping("/update")
	public Object update(Building building) throws Exception {

		FindOne<Building> find = jdbcSession.findOne(Building.class)
				.eq("deleted", false)
				.eq("communityNo", building.getCommunityNo())
				.eq("name", building.getName())
				.noEq("id", building.getId());

		if(Objects.nonEmpty(building.getUnitName())){
			find.eq("unitName", building.getUnitName());
		}

		Building item = find.exe();

		if(Objects.nonNull(item)){
			return Result.error(0, "当前小区下已有相同的楼栋信息，请修改后重试");
		}

		List<House> houses = jdbcSession.findArray(House.class)
				.eq("communityNo", building.getCommunityNo())
				.eq("buildNo",building.getId())
				.exe();

		houses.forEach(house -> {
			house.setBuildName(building.getName());
			house.setUnitName(building.getUnitName());
		});
		jdbcSession.updateById(houses);

		Community com = Pool.get(Community.class, building.getCommunityNo());
		building.setDepartmentNo(com.getParent_id());
		building.setDepartmentNos(com.getParent_ids());

		jdbcSession.updateById(building);
		return Result.success();
	}

    @ReqMapping("/delete")
	public Object delete(Building item) {
		List<House> houses = jdbcSession.findArray(House.class)
				.eq("communityNo", item.getCommunityNo())
				.eq("buildNo", item.getId())
				.eq("deleted", false)
				.exe();

		if(Objects.nonEmpty(houses)){
			return Result.error(0, "需先删除该楼栋下的房屋，再删除该楼栋！");
		}


		item.setDeleted(true);
		jdbcSession.updateById(item);

		return Result.success();
	}

	public List<String> getChildDepartments(List<String> departments) throws Exception {
		JSONObject result = doveClient.post("/basic/department/service/getChildDepartments", http->{
			JSONObject body = new JSONObject();
			body.put("pidList", departments);
			http.setBody(body.toString());
		});

		if (result.getIntValue("code") == 200) {
			JSONArray data = result.getJSONArray("data");
			if(Objects.nonEmpty(data)){
				return JSONObject.parseArray(data.toJSONString(), String.class);
			}
		}
		return new ArrayList<>();
	}

}
